package com.jh.paymentchannel.service;

import java.math.BigDecimal;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import cn.jh.common.tools.Tools;
import cn.jh.common.utils.CommonConstants;

import com.jh.paymentchannel.business.TopupPayChannelBusiness;
import com.jh.paymentchannel.pojo.ChannelDetail;
import com.jh.paymentchannel.pojo.TopupPayChannelRoute;
import com.jh.paymentchannel.util.Util;
import com.jh.paymentchannel.util.WithDrawOrder;


@Controller
@EnableAutoConfiguration
public class PayService {

	
	private static final Logger log = LoggerFactory.getLogger(PayService.class);
	
	
	@Autowired
	private TopupPayChannelBusiness  topupPayChannelBusiness;
	
	
	@Autowired
	private PaymentChannelFactory factory;
	
	@Autowired
	private Util util;
	
	/***请求url, 并返回跳装的url*/
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/paymentchannel/pay/request")
	public @ResponseBody Object payrequest(HttpServletRequest request, 
			@RequestParam(value = "ordercode") String ordercode,
			@RequestParam(value = "cardno") String cardno,
			@RequestParam(value = "username") String username,
			@RequestParam(value = "amount") String amount,
			@RequestParam(value = "bankname") String bankname,
			@RequestParam(value = "phone") String phone,						
			@RequestParam(value = "pri_or_pub", required = false, defaultValue = "0") String priOrpub,			
			@RequestParam(value = "brandcode", required = false, defaultValue = "0") String brandcode,//品牌id
			@RequestParam(value = "channel_type", required = false, defaultValue = "2") String channelType,	//0充值1代付
			@RequestParam(value = "channel_tag", required = false, defaultValue = "YILIAN") String channelTag//渠道标识
			){
		
		String notifyURL;
		String returnURL;
		Map map = new HashMap();
		
		if(Tools.checkAmount(amount) == false){
			
			map.put(CommonConstants.RESP_CODE,CommonConstants.ERROR_AMOUNT_ERROR);
			map.put(CommonConstants.RESP_MESSAGE, "支付金额有错");
			return map;
		}
		
		
		TopupPayChannelRoute payChannelRoute = topupPayChannelBusiness.getTopupChannelByBrandcode(brandcode, channelType, channelTag);
		log.info("TopupPayChannelRoute--RESULT================"+payChannelRoute);
		URI uri = util.getServiceUrl("user", "error url request!");
		String url = uri.toString() + "/v1.0/user/channel/query";
		
		/**根据的渠道标识或去渠道的相关信息*/
		MultiValueMap<String, String> requestEntity  = new LinkedMultiValueMap<String, String>();
		requestEntity.add("channel_tag", channelTag);
		RestTemplate restTemplate=new RestTemplate();
		String resultObjx = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("接口/v1.0/user/channel/query--RESULT================"+resultObjx);
		JSONObject jsonObject =  JSONObject.fromObject(resultObjx);
		JSONObject resultObj  =  jsonObject.getJSONObject("result");
		String channelid  = resultObj.getString("id");		
		ChannelDetail channelDetail = topupPayChannelBusiness
				.getChannelDetailByTag(payChannelRoute.getTargetChannelTag());
		notifyURL = channelDetail.getNotifyURL();
		returnURL = channelDetail.getReturnURL();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/brandrate/query";
		/**根据的渠道标识或去渠道的相关信息*/
		requestEntity  = new LinkedMultiValueMap<String, String>();
		requestEntity.add("brand_id", brandcode);
		requestEntity.add("channel_id", channelid);
		restTemplate=new RestTemplate();
		resultObjx = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("接口/v1.0/user/brandrate/query--RESULT================"+resultObjx);
		jsonObject =  JSONObject.fromObject(resultObjx);
		resultObj  =  jsonObject.getJSONObject("result");
		String  withdrawFee  = resultObj.getString("withdrawFee");	
		String  extraFee  = resultObj.getString("extraFee");	
		
						
		PayRequest  paymentRequest = factory.getPayChannelRequest(payChannelRoute.getTargetChannelTag());
		
		WithDrawOrder withdrawOrder = paymentRequest.payRequest(ordercode, cardno, username, new BigDecimal(amount).subtract(new BigDecimal(withdrawFee)).subtract(new BigDecimal(extraFee)).toString(), bankname, phone, priOrpub, notifyURL,returnURL);
		/**
		 * 如果是E秒付
		 * **/
		if(withdrawOrder.getReqcode().length()==4){
			map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
			map.put(CommonConstants.RESULT, withdrawOrder);
			map.put(CommonConstants.RESP_MESSAGE, "下单成功");
			return map;
		}
		/**
		 * 如果是联动
		 * **/
		if(withdrawOrder.getReqcode().length()==5){
			map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
			map.put(CommonConstants.RESULT, withdrawOrder);
			map.put(CommonConstants.RESP_MESSAGE, "下单成功");
			return map;
		}
		
		if(withdrawOrder.getReqcode().equalsIgnoreCase(CommonConstants.SUCCESS)){
			map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
			map.put(CommonConstants.RESULT, withdrawOrder);
			map.put(CommonConstants.RESP_MESSAGE, "下单成功");
		}else{
			
			map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_WITHDRAW_ORDER_FAIL);
			map.put(CommonConstants.RESULT, withdrawOrder);
			map.put(CommonConstants.RESP_MESSAGE, "下单失败");
			
		}
		
		return map;
		
	}
	
	
	
	
	
	
	/**代付结果查询*/
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/paymentchannel/pay/query")
	public @ResponseBody Object payquery(HttpServletRequest request, 
			@RequestParam(value = "ordercode") String ordercode,
			@RequestParam(value = "brandcode", required = false, defaultValue = "0") String brandcode,
			@RequestParam(value = "channel_type", required = false, defaultValue = "2") String channelType,	
			@RequestParam(value = "channel_tag", required = false, defaultValue = "YILIAN") String channelTag){
	
			Map map = new HashMap();
			TopupPayChannelRoute payChannelRoute = topupPayChannelBusiness.getTopupChannelByBrandcode(brandcode, channelType, channelTag);
			PayRequest  paymentRequest = factory.getPayChannelRequest(payChannelRoute.getTargetChannelTag());
			log.info("paymentRequest--RESULT================"+paymentRequest);
			WithDrawOrder   withdrawOrder = paymentRequest.queryPay(ordercode);
			log.info("withdrawOrder--RESULT================"+withdrawOrder);
			if(withdrawOrder.getReqcode().equalsIgnoreCase(CommonConstants.SUCCESS)){
				map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
				map.put(CommonConstants.RESULT, withdrawOrder);
				map.put(CommonConstants.RESP_MESSAGE, "交易成功");
			}else{
				map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_WITHDRAW_ORDER_FAIL);
				map.put(CommonConstants.RESULT, withdrawOrder);
				map.put(CommonConstants.RESP_MESSAGE, "交易失败");
			}
			
			return map;
		
	}
	
	
	
	
	
}
